import React, { useState } from 'react'
import { Editor } from '@tinymce/tinymce-react' // 使用 TinyMCE 作为富文本编辑器
import { TINY_API_KEY, UPLOAD_API, BLOG_TYPE_MAP } from '~/const/index'
import toast from '~/utils/toast'
import { postPublishBlogXhr } from '~/api/index'
import { getUserInfo } from '~/utils/crypto'
import { useNavigate } from 'react-router-dom' // 新增

const PublishPage: React.FC = () => {
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [editorLoaded, setEditorLoaded] = useState(false)
  const [category, setCategory] = useState('tech') // 默认选择第一个类别
  const navigate = useNavigate()
  const handleEditorChange = (content: string) => {
    setContent(content)
  }
  const handleImageUpload = (
    blobInfo: any,
    progress?: (percent: number) => void
  ): Promise<string> => {
    return new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', blobInfo.blob(), blobInfo.filename())

      fetch(UPLOAD_API, {
        method: 'POST',
        body: formData,
      })
        .then((response) => response.json())
        .then((result) => {
          if (result?.file?.path) {
            resolve(result.file.path)
          } else {
            toast.error('上传失败')
            reject('上传失败')
          }
        })
        .catch(() => {
          toast.error('上传失败')
          reject('上传失败')
        })
    })
  }

  const handleSubmit = async () => {
    if (!title) {
      toast.info('请输入博客标题')
      return
    }
    if (!content) {
      toast.info('请输入博客内容')
      return
    }

    // 获取登录用户信息
    const userInfo = getUserInfo() || {}
    // 发布博客
    const blogData = {
      title,
      content,
      category,
      tags: [],
      authorId: userInfo?.id || '',
      authorName: userInfo?.nickname || userInfo?.username || '',
      authorAvatar: userInfo?.avatar || '',
    }

    try {
      const response = await postPublishBlogXhr(blogData)
      if (response.code === 200) {
        toast.success('文章发布成功')
        // 回到文章列表
        navigate('/articles')
      } else {
        toast.error(`发布失败: ${response.message}`)
      }
    } catch (error) {
      toast.error('发布失败: 网络错误或服务器未响应')
    }
  }
  return (
    <div className="container px-6 py-2">
      <div className="flex items-center justify-between">
        <div className="text-2xl font-bold mb-2">发布文章</div>
        <div className="flex items-center">
          分类：
          <select
            value={category}
            onChange={(e) => setCategory(e.target.value)}
            className="mr-4  px-2 border border-gray-300 rounded"
          >
            {Object.entries(BLOG_TYPE_MAP).map(([key, value]: any) => (
              <option key={key} value={key}>
                {value}
              </option>
            ))}
          </select>
          <button
            onClick={handleSubmit}
            className="mb-2 bg-blue-500 text-white py-2 px-4 rounded-lg text-base"
          >
            发布
          </button>
        </div>
      </div>

      <input
        type="text"
        placeholder="输入标题"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        className="w-full mb-4 p-2 border border-gray-300 rounded"
      />
      {!editorLoaded && (
        <div
          className="w-full bg-gray-100 flex items-center justify-center"
          style={{ height: '650px' }}
        >
          <span>加载编辑器中...</span>
        </div>
      )}
      <Editor
        apiKey={TINY_API_KEY}
        value={content}
        init={{
          height: 650,
          menubar: true,
          plugins: [
            'advlist',
            'autolink',
            'lists',
            'link',
            'image',
            'charmap',
            'preview',
            'anchor',
            'searchreplace',
            'visualblocks',
            'code',
            'fullscreen',
            'insertdatetime',
            'media',
            'table',
            'help',
            'wordcount',
          ],
          toolbar: [
            'undo redo | formatselect | bold italic backcolor',
            'alignleft aligncenter alignright alignjustify',
            'bullist numlist outdent indent | image | help',
          ].join(' | '),
          images_upload_handler: handleImageUpload, // 设置图片上传处理函数
          paste_data_images: true,
          automatic_uploads: true,
          images_reuse_filename: true,
          convert_urls: false,
          relative_urls: false,
          remove_script_host: false,
          setup: (editor: any) => {
            editor.on('init', () => {
              setEditorLoaded(true)
            })
          },
        }}
        onEditorChange={handleEditorChange}
      />
    </div>
  )
}

export default PublishPage
